package stat

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"navi-mumbai/common/gensql"
)

var _ LifeTimeValueModel = (*customLifeTimeValueModel)(nil)

type (
	// LifeTimeValueModel is an interface to be customized, add more methods here,
	// and implement the added methods in customLifeTimeValueModel.
	LifeTimeValueModel interface {
		lifeTimeValueModel
		UpdateLoginUserCnt(ctx context.Context, statDay int64, day, loginCnt int64) error
		Find(ctx context.Context, statDayStart, statDayEnd, pageNo, pageSize int64) ([]*LifeTimeValue, error)
	}

	customLifeTimeValueModel struct {
		*defaultLifeTimeValueModel
		genSql *gensql.GenSql
	}
)

// NewLifeTimeValueModel returns a model for the database table.
func NewLifeTimeValueModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) LifeTimeValueModel {
	return &customLifeTimeValueModel{
		defaultLifeTimeValueModel: newLifeTimeValueModel(conn, c, opts...),
		genSql:                    gensql.NewGenSql(),
	}
}

func (m *customLifeTimeValueModel) UpdateLoginUserCnt(ctx context.Context, statDay int64, day, loginCnt int64) error {
	q := fmt.Sprintf("update %s set day%d_login_count = ? where stat_day = ?", m.table, day)
	_, err := m.ExecNoCacheCtx(ctx, q, loginCnt, statDay)
	return err
}

func (m *customLifeTimeValueModel) Find(ctx context.Context, statDayStart, statDayEnd, pageNo, pageSize int64) ([]*LifeTimeValue, error) {
	query := fmt.Sprintf("select %s from %s ", lifeTimeValueRows, m.table)
	m.genSql.InitSql(query)
	if statDayStart != 0 {
		m.genSql = m.genSql.Where("stat_day >= ?", statDayStart)
	}
	if statDayEnd != 0 {
		m.genSql = m.genSql.Where("stat_day <= ?", statDayEnd)
	}

	q, v, err := m.genSql.OrderBy("create_time desc").Limit(uint64(pageSize)).Offset(uint64((pageNo - 1) * pageSize)).ToSql()
	if err != nil {
		return nil, err
	}

	resp := make([]*LifeTimeValue, 0)
	err = m.QueryRowsNoCacheCtx(ctx, &resp, q, v...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}
